import type { RouteRecordRaw } from 'vue-router';

import { useAppStore } from '/@/store/modules/app';
import { usePermissionStore } from '/@/store/modules/permission';
import { useUserStore } from '/@/store/modules/user';

import { useTabs } from './useTabs';

import { router, resetRouter } from '/@/router';

import projectSetting from '/@/settings/projectSetting';
import { PermissionModeEnum } from '/@/enums/appEnum';

import { intersection } from 'lodash-es';
import { isArray } from '/@/utils/is';
import { useMultipleTabStore } from '/@/store/modules/multipleTab';

// User permissions related operations
export function usePermission() {
  const userStore = useUserStore();
  const appStore = useAppStore();
  const permissionStore = usePermissionStore();
  const { closeAll } = useTabs(router);

  /**
   * Change permission mode
   */
  async function togglePermissionMode() {
    appStore.setProjectConfig({
      permissionMode:
        projectSetting.permissionMode === PermissionModeEnum.BACK
          ? PermissionModeEnum.ROUTE_MAPPING
          : PermissionModeEnum.BACK,
    });
    location.reload();
  }

  /**
   * Reset and regain authority resource information
   * 重置和重新获得权限资源信息
   * @param id
   */
  async function resume() {
    const tabStore = useMultipleTabStore();
    tabStore.clearCacheTabs();
    resetRouter();
    const routes = await permissionStore.buildRoutesAction();
    routes.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw);
    });
    permissionStore.setLastBuildMenuTime();
    closeAll();
  }

  /**
   * Determine whether there is permission
   */
  function hasPermission(path?: string, value?: string | string[], def = true): boolean {
    // Visible by default
    if (!path || !value) {
      return def;
    }
    const permMode = projectSetting.permissionMode;
    if (
      [PermissionModeEnum.ROUTE_MAPPING, PermissionModeEnum.ROLE, PermissionModeEnum.BACK].includes(
        permMode,
      )
    ) {
      const componentPermissionList = userStore.getComponentPermissionList;
      if (componentPermissionList) {
        for (const componentPermission of componentPermissionList) {
          if (componentPermission.componentCodes) {
            if (componentPermission && componentPermission.componentCodes) {
              if (path === componentPermission.routerPath) {
                if (!isArray(value)) {
                  return componentPermission.componentCodes.includes(value as string);
                } else {
                  return (
                    (intersection(value, componentPermission.componentCodes) as string[]).length > 0
                  );
                }
              }
            }
          }
        }
      }
    }
    return false;
  }

  /**
   * refresh menu data
   */
  async function refreshMenu() {
    resume();
  }

  return { hasPermission, togglePermissionMode, refreshMenu };
}
